package cn.le.springAnnotationCustomize.annotationUtil;

import cn.le.springAnnotationCustomize.annotation.CustomerRule;
import cn.le.springAnnotationCustomize.annotation.DateString;

import javax.xml.crypto.Data;
import java.lang.annotation.Annotation;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by admin on 2017/3/30.
 */
@CustomerRule
public class DateValidatorRule extends  AbastractCustomerValidatorRule {
    @Override
    public boolean support(Annotation annotation) {
        return annotation instanceof DateString;
    }

    @Override
    public void validProperty(Annotation annotation, Object property, PostHandler postHandler) {
        DateString dateString = (DateString) annotation;
        //验证日期格式是否满足注解要求
        if(parse(dateString.pattern(), (String) property) == null)
        {
            postHandler.postHanle(dateString.errorCode(),dateString.message());
        }
    }

    /**
     * 验证日期格式
     * @param pattern 日期格式
     * @param property 日期
     * @return
     */
    private Date parse(String pattern, String property)
    {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            return sdf.parse(property);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

}
